package com.xuhj.export.factory;

import com.xuhj.common.CommonUtils;
import com.xuhj.common.ExcelFileType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.lang.reflect.Method;
import java.util.List;

public class ExcelFactory {
    public static Workbook createExcel(List data, @ExcelFileType String type) throws Exception {
        if (data == null || data.size() == 0) {
            throw new Exception("数据不能为空");
        }
        //根据类型生成工作簿
        Workbook workbook = (Workbook) Class.forName(type).newInstance();
        //新建表格
        Sheet sheet = workbook.createSheet();
        //生成表头
        Row thead = sheet.createRow(0);
        String[] fieldsName = CommonUtils.getFieldsName(data.get(0).getClass());
        for (int i = 0; i < fieldsName.length; i++) {
            Cell cell = thead.createCell(i);
            cell.setCellValue(fieldsName[i]);
        }
        //保存所有属性的getter方法名
        Method[] methods = new Method[fieldsName.length];
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Object obj = data.get(i);
            for (int j = 0; j < fieldsName.length; j++) {
                //加载第一行数据时，初始化所有属性的getter方法
                if (i == 0) {
                    String fieldName = fieldsName[j];
                    //处理布尔值命名 "isXxx" -> "setXxx"
                    if (fieldName.contains("is")) {
                        fieldName = fieldName.split("is")[1];
                    }
                    methods[j] = obj.getClass().getMethod("get" +
                            fieldName.substring(0, 1).toUpperCase() +
                            fieldName.substring(1));
                }
                Cell cell = row.createCell(j);
                Object value = methods[j].invoke(obj);
                //注意判断 value 值是否为空
                if (value == null) {
                    value = "无";
                }
                cell.setCellValue(value.toString());
            }
        }
        return workbook;
    }
}
